package com.qf.smsplatform.webmaster.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.qf.smsplatform.common.constants.CacheConstants;
import com.qf.smsplatform.webmaster.dao.TChannelMapper;
import com.qf.smsplatform.webmaster.dao.TClientBusinessMapper;
import com.qf.smsplatform.webmaster.dao.TClientChannelMapper;
import com.qf.smsplatform.webmaster.dto.DataGridResult;
import com.qf.smsplatform.webmaster.dto.QueryDTO;
import com.qf.smsplatform.webmaster.pojo.*;
import com.qf.smsplatform.webmaster.service.ClientChannelService;
import com.qf.smsplatform.webmaster.service.api.CacheService;
import com.qf.smsplatform.webmaster.util.JsonUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.*;

@Service
public class ClientChannelServiceImpl implements ClientChannelService {

    @Resource
    private TClientChannelMapper tClientChannelMapper;
    @Resource
    private TClientBusinessMapper tClientBusinessMapper;

    @Resource
    private TChannelMapper tChannelMapper;

    @Resource
    private CacheService cacheService;

    @Override
    public int addClientChannel(TClientChannel tClientChannel) {
        int i =  tClientChannelMapper.insertSelective(tClientChannel);
        Map<String, String> stringObjectMap = JsonUtils.objectToMap(tClientChannel);
        cacheService.hMSet("ROUTER:"+tClientChannel.getClientid(),stringObjectMap);
        return i;
    }

    @Override
    public int delClientChannel(Long id) {
        TClientChannel tClientChannel = findById(id);
        cacheService.del("ROUTER:"+tClientChannel.getClientid());
        return tClientChannelMapper.deleteByPrimaryKey(id);
    }

    @Override
    public int updateClientChannel(TClientChannel tClientChannel) {
        int i = tClientChannelMapper.updateByPrimaryKey(tClientChannel);
        if (i > 0) {
//            tClientChannel.setCorpname("");
//            tClientChannel.setChannelname("");
            Map stringObjectMap = JsonUtils.objectToMap(tClientChannel);
            cacheService.hMSet("ROUTER:" + tClientChannel.getClientid(), stringObjectMap);
        }
        return i;
    }

    @Override
    public TClientChannel findById(Long id) {
        return tClientChannelMapper.selectByPrimaryKey(id);
    }

    @Override
    public List<TClientChannel> findAll() {
        return tClientChannelMapper.selectByExample(null);
    }

    @Override
    public DataGridResult findByPage(QueryDTO queryDTO) {
        PageHelper.offsetPage(queryDTO.getOffset(), queryDTO.getLimit());
        TClientChannelExample example = new TClientChannelExample();
        String sort = queryDTO.getSort();
        if (!StringUtils.isEmpty(sort)) {
            example.setOrderByClause("id");
        }
        List<TClientChannel> tClientChannels = tClientChannelMapper.selectByExample(example);
        for (TClientChannel tClientChannel : tClientChannels) {
            Long clientid = tClientChannel.getClientid();
            TClientBusiness tClientBusiness = tClientBusinessMapper.selectByPrimaryKey(clientid);
            String corpname = tClientBusiness.getCorpname();
            tClientChannel.setCorpname(corpname);
            long channelid = (long)tClientChannel.getChannelid();
            TChannel tChannel = tChannelMapper.selectByPrimaryKey(channelid);
            String channelname = tChannel.getChannelname();
            tClientChannel.setChannelname(channelname);
        }
        PageInfo<TClientChannel> info = new PageInfo<>(tClientChannels);
        long total = info.getTotal();
        DataGridResult result = new DataGridResult(total, tClientChannels);
        return result;
    }



    //    @Override
//    public boolean syncAllDataToCache() {
//        List<TClientChannel> clientChannelList = findAll();
//        for (TClientChannel tClientChannel : clientChannelList) {
//            Map stringObjectMap = JsonUtils.objectToMap(tClientChannel);
//            cacheService.hMSet(CacheConstants.CACHE_PREFIX_ROUTER+tClientChannel.getClientid(),stringObjectMap);
//        }
//       return true;
//    }

    //SELECT tcc.clientId clientId,tc.id channelId,tc.spNumber spNumber,tcc.extendNumber extendNumber,tcc.price fee,tc.channelType channelType from t_channel tc INNER JOIN t_client_channel tcc where tc.id = tcc.channelId
    //同步客户绑定的通道信息到缓存
    @Override
    public boolean sync() {
        //调用mapper查询出所有通道信息包括指定要映射的字段（clientID,channelId,spNumber,extendNumber,fee,channelType）
        Set<ClientChannelStrategy> clientChannelStrategies = tClientChannelMapper.findClientChannel();
        //将CHANNEL:+clientId作为key，value使用set结构存储客户绑定的通道信息,这里创建map来对应
        Map<String, Set<ClientChannelStrategy>> data = new HashMap<String, Set<ClientChannelStrategy>>();
        //遍历查询到的信息存入到map中
        for (ClientChannelStrategy clientChannelStrategy : clientChannelStrategies) {
            Set<ClientChannelStrategy> set = data.get(clientChannelStrategy.getClientId()+"");
            if(set == null){
                // 没有给set设置数据
                set = new HashSet<>();
                set.add(clientChannelStrategy);
                data.put(clientChannelStrategy.getClientId() + "",set);
            }else{
                // 当前clientID中已经有对应的ClientChannelStrategy对象的数据
                set.add(clientChannelStrategy);
            }
        }
        //封装好的map同步到redis中
        for (Map.Entry<String, Set<ClientChannelStrategy>> entry : data.entrySet()) {
            //准备同步redis的key
            String key = CacheConstants.CACHE_PREFIX_SMS_CHANNEL+entry.getKey();
            //准备同步redis的value
            Set<ClientChannelStrategy> value = entry.getValue();
            //调用cache模块进行同步
            cacheService.saddObject(key,value.toArray());
        }
        return true;
    }

}
